<template>
  <div>
    <div class="bold inner-box btn bold" @click="showModal = !showModal">SKU预览</div>

    <a-modal :visible="showModal" style="top: 20px;" width="90%" title="SKU预览" :footer="null" @cancel="handleOk">

      <div class=" box">
        <div class="box_back">
          <a-radio-group v-model:value="exportType">
            <a-radio-button value="pic">导出图片</a-radio-button>
            <a-radio-button value="table">导出表格</a-radio-button>
          </a-radio-group>

          <a-row style="line-height: 30px; align-items: center; margin: 10px 0;">
            <a-col :flex="2">
              <a-flex gap="middle">
                <p>类目ID: <span>{{ classifyId }}</span></p>
                <p>商品ID: {{ item.itemId() }} <span></span></p>
              </a-flex>
            </a-col>
            <a-col :flex="3" style="display: flex; justify-content: flex-end;">
              <div data-v-6f2bc18b="" class="dts_alert">
                星察数据视下载文件和数据仅供学习与参考，切勿私自商用造成侵权后果！
              </div>
              <a-button v-show="exportType == 'pic'" @click="downloadImages">
                <template #icon>
                  <PictureOutlined />
                </template>
                导出图片
              </a-button>
            </a-col>
          </a-row>

          <!-- 组件 -->
          <export-image v-show="exportType == 'pic'" :skuData="skuData"></export-image>
          <export-table v-show="exportType != 'pic'" :skuData="skuData"></export-table>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import ExportImage from '~/contentScripts/views/tao/detail/components/analysis/components/skuView/exportImage.vue'
import ExportTable from "./components/skuView/exportTable.vue"

import { TRequest } from '~/utils/ali/PCRequest';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';

import { ref, getCurrentInstance, onMounted } from 'vue';

// const __option = getCurrentInstance()?.appContext.provides.option;

// const instance = getCurrentInstance()

// 弹框
let showModal = ref<boolean>(false);
let skuData = reactive<Array<any>>([])
let classifyId = ref<number | string>('')
// 导出切换
let exportType = ref<string>('pic')

const getItem = () => {
  const instance = getCurrentInstance();
  const item = (instance?.proxy as { $item?: any }).$item ?? {};
  return item;
}
const item = getItem();

// 获取数据
const getData = () => {
  TRequest.skuList(item.itemId()).then(res => {

    let skuBase = res.skuBase;   // 类ID
    let skuCore = res.skuCore;   // 库存
    // 类目ID
    classifyId.value = res.pcTrade.pcBuyParams.rootCatId;

    // 处理数据
    // 类ID
    skuBase.skus.forEach((item) => {
      let skus = item.propPath.split(';');
      let pid = skus.map(itm => itm.split(':')[0]);
      let vid = skus.map(itm => itm.split(':')[1]);
      skuData.push({ 'SKUID': item.skuId, 'pid': pid, 'vid': vid });
    });
    // 规格类型
    let classifyValArr = skuBase.props;
    // 规格样式
    skuData.forEach((item, index) => {
      skuData[index].skuVal = [];

      item.pid.forEach((pid) => {
        let prop = classifyValArr.find(ele => ele.pid === pid);
        if (prop) {
          skuData[index].skuVal.push({ key: prop.name, });
        }
      });

      item.vid.forEach((vid, indx) => {
        classifyValArr.forEach(ele => {
          let value = ele.values.find(itVid => itVid.vid === vid);
          if (value) {
            skuData[index].skuVal[indx].value = value.name;
            skuData[index].image = value.image && !skuData[index].image ? value.image : skuData[index].image;
          }
        });
      });
    });
    // 库存
    for (const key in skuCore.sku2info) {
      if (Object.hasOwnProperty.call(skuCore.sku2info, key)) {
        const element = skuCore.sku2info[key];
        skuData.forEach((item, index) => {
          if (key == item.SKUID) {
            skuData[index].query = element.quantity;
            skuData[index].price = element.price.priceText;
          }
        })
      }
    };
  })
}

// 关闭弹框
const handleOk = (e: MouseEvent) => {
  // console.log(e);
  showModal.value = false;
};

// 下载压缩1
const downloadImages = async () => {

  const zip = new JSZip();
  let urls = []; // 用实际的图片链接替换这里的示例链接

  urls = skuData.map(item => item.image + '_sum.jpg');

  const promises = urls.map(async (url, index) => {
    const response = await fetch(url);
    const blob = await response.blob();
    let filename = ''; // 获取图片文件名
    skuData[index].skuVal.forEach(item => {
      filename += item.value;
    })
    zip.file(filename+'.jpg', blob); // 将图片添加到 zip 文件中，可以根据需求修改文件名称
  });

  await Promise.all(promises);

  zip.generateAsync({ type: 'blob' })
    .then((content) => {
      saveAs(content, '星察数据 SKU预览' + item.itemId()); // 下载 zip 文件
    });
}

onMounted(() => {
  getData();
})

</script>
<style scoped lang="less">
.box {
  width: 100%;
  height: 80vh;
  overflow-y: auto;
  // background-color: #eeeeee;


  .box_back {
    width: 99%;
    margin: 10px auto;
    padding: 10px;
    box-sizing: border-box;
    background-color: #fff;

    .dts_alert {
      width: 450px;
      padding: 3px 8px;
      border-radius: 4px;
      color: #fff;
      font-size: 12px;
      background: linear-gradient(90deg, #40a9ff, #40a9ff, #fff);
    }
  }
}
</style>